<?php

namespace App\Models;

use DB;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Services\WoChatService;


class Employee extends Model
{
	use SoftDeletes;
	protected $fillable = ['user_id', 'shop_id', 'name', 'avatar', 'introduce', 'remarks', 'clue_weight', 'seat', 'separated_at'];
    // protected $casts = [
    //     'separated_at'  => 'datetime:Y-m-d',
    // ];

    // 员工管理：在职、全职、实习、劳务、顾问、返聘、外包、兼职 | 试用、正式 | 待入职、待离职、已离职
    // 薪资档案：在职、全职、实习、劳务、顾问、返聘、外包、兼职、试用、正式

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function shop()
    {
        return $this->belongsTo(Shop::class);
    }

    public function shopPosition()
    {
        return $this->belongsTo(ShopPosition::class);
    }

    public function enrollment()
    {
        return $this->hasOne(Enrollment::class)->latest();
    }

    public function position()
    {
        return $this->hasOne(TransferPosition::class)->latest();
    }

    public function salary()
    {
        return $this->hasOne(Salary::class)->latest();
    }

    public function contract()
    {
        return $this->hasOne(EmploymentContract::class)->latest();
    }

    public function insurances()
    {
        return $this->hasMany(Insurance::class);
    }

    public function wochatUsers()
    {
        return $this->hasMany(WochatUser::class);
    }

    public function insuranceFunds()
    {
        return $this->hasMany(InsuranceFund::class);
    }

    public function transferPositions()
    {
        return $this->hasMany(TransferPosition::class);
    }

    public function salaryConfigs()
    {
        return $this->hasMany(SalaryConfig::class);
    }

    public function performanceObjectives()
    {
        return $this->hasMany(PerformanceObjective::class);
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'employee_role_relation', 'employee_id', 'role_id');
    }

    public function getIsAdminAttribute()
    {
        return $this->roles()->whereId(1)->exists();
    }

    public function scopeWhichKeyword($q, $k)
    {
        if (!$k) return $q;
        return $q->where(self::qualifyColumn('name'), 'like', "%{$k}%");
    }

    public function scopeWhichShop($q, $s)
    {
        if (!$s) return $q;
        if (!is_array($s)) {
            if (!is_numeric($s)) return $q;
            $s = [$s];
        }
        return $q->whereIn(self::qualifyColumn('shop_id'), $s);
    }
    
    public function scopeWhichRole($q, $i)
    {
        if (! $i) return $q;
        if (!is_array($i)) {
            $i = [$i];
        }
        return $q->whereHas('roles', function ($q) use($i) {
            return $q->whereIn('roles.id', $i);
        });
    }

    public function scopeWhichType($q, $i)
    {
        if (! $i) return $q;
        if (!is_array($i)) {
            $i = [$i];
        }
        return $q->whereIn('enrollment.type', $i);
    }

    public function scopewhichOfficial($q, $i)
    {
        if (!isset($i)) return $q;
        return $q->where('position.official', $i);
    }

    public function scopewhichGender($q, $i)
    {
        if (!isset($i)) return $q;
        return $q->where('enrollment.gender', $i);
    }

    // public function scopeWhichPosition($q, $s)
    // {
    //     if (!$s) return $q;
    //     if (!is_array($s)) {
    //         if (!is_numeric($s)) return $q;
    //         $s = [$s];
    //     }
    //     $q->whereIn(self::qualifyColumn('shop_position_id'), $s);
    // }

    public function scopeWhichStatus($q, $s)
    {
        switch ($s) {
            case 'unrecorded':
                // 待入职。即未登记入职档案
                // return $q->whereDoesntHave('enrollment');
                return $q->whereNull('enrollment.id');
                break;
            
            case 'recording':
                // 入职中。即正在办理入职登记，待审核/审核中/已驳回等未通过审核状态
                return $q->whereNotNull('enrollment.id')->where('enrollment.status', '!=', 4);
                break;
            
            case 'recorded':
                // 已入职。即已通过审核入职档案，未申请离职
                // return $q->whereNotNull('enrollment.id')->where('enrollment.status', 4)->whereNull('departure.id');
                return $q->whereNotNull('enrollment.id')->where('enrollment.status', 4)->whereNull('employees.separated_at');
                break;
            
            case 'quitting':
                // 离职中。即正在办理离职，待审核/审核中/已驳回等未通过审核状态
                return $q->whereNull('employees.separated_at')->whereNotNull('departure.id');
                break;
            
            case 'quitted':
                // 已离职。即已通过审核离职申请
                return $q->whereNotNull('employees.separated_at');
                break;
            
            default:
                return $q;
                break;
        }
        return $q->whereIn(self::qualifyColumn('shop_id'), $s);
    }

    public function scopeWhichAt($q, $a, $d)
    {
        $at = "{$a}_at";
        if (! in_array($at, ["updated_at", "created_at"])) return $q;
        $field = self::qualifyColumn($at);
        if (! is_array($d)) return $q->orderByDesc($field);
        if ($d[0]) $q->where($field, '>=', $d[0]);
        if ($d[1]) $q->where($field, '<=', $d[1]);
    }

    public function findOa()
    {
        if (!$shop = Shop::select('oa_type', 'oa_id')->find($this->shop_id)) return $this->res(1, "未找到关联站点！");
        // 找出当前业务所在公司使用OA(企业微信/钉钉/飞书等第三方OA)
        switch ($shop->oa_type) {
            case 'App\\Models\\WochatApp':
                // 找OA应用
                $app = WochatApp::with('wechatApp:id,corpid')->select('id', 'wechat_app_id', 'secret', 'agentid')->find($shop->oa_id);
                if (!$app) return $this->res(1, "未找到应用！");
                // 找OA联系人
                $creator = WochatUser::where('wechat_app_id', $app->wechatApp->id)->where('employee_id', $this->id)->select('userid', 'name')->first();
                if (!$creator || !$creator->userid) return $this->res(1, "未找到OA联系人！");
                // 返回要与OA信息
                return $this->res(0, "ok", [
                    // 企业ID
                    'corpid' => $app->wechatApp->corpid,
                    // 通讯密钥
                    'secret' => $app->secret,
                    // 应用ID
                    'agentid' => $app->agentid,
                    // 用户ID
                    'userid' => $creator->userid,
                    'name'  => $creator->name,
                    // OA类型
                    'type' => 'wechat'
                ]);
            break;

            default:
                return $this->res(1, "未知OA类型");
            break;
        }
    }

    public function auth($p, $a = 'default')
    {
        $p = str_replace('adminv1/', '', $p);
        $permissions = config('citys.permissions');
        if (isset($permissions[$p]) && in_array($a, $permissions[$p])) return true;
        // 弃用从 user 关联角色权限
        // return DB::table('permissions as p')
        //     ->rightJoin('role_permission_relation as r_p', 'r_p.permission_id', '=', 'p.id')
        //     ->rightJoin('employee_role_relation as e_r', 'e_r.role_id', '=', 'r_p.role_id')
        //     ->rightJoin('roles as r', 'r.id', '=', 'r_p.role_id')
        //     ->where('e_r.employee_id', $this->id)
        //     ->where('r.shop_id', $this->shop_id)
        //     ->where('p.action', $a)
        //     ->where('p.api', $p)
        //     ->exists();
        return DB::table('permissions as p')
            ->rightJoin('role_permission_relation as r_p', 'r_p.permission_id', '=', 'p.id')
            ->rightJoin('employee_role_relation as e_r', 'e_r.role_id', '=', 'r_p.role_id')
            ->where('e_r.employee_id', $this->id)
            ->where('p.action', $a)
            ->where('p.api', $p)
            ->exists();
    }

    protected function res($code = '0', $msg = 'ok', $result = []) {
        return compact('code', 'msg', 'result');
    }
}
